package com.feituan.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.feituan.core.pojo.response.Response;

import com.feituan.wx.storage.Storage;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoProperties;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/file")
@Api(tags = "文件管理")
public class FileController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private Storage storage;


    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {

        // 检查文件大小 2MB的大小限制
        if (file.getSize() > 2 * 1024 * 1024) {
            // 返回文件过大的错误信息
            return "File size exceeds limit (2MB)";
        }

        logger.info("upload start,file:{}", file.getOriginalFilename());

        String originalFilename = file.getOriginalFilename();
        String key = generateKey(originalFilename);
        storage.store(file.getInputStream(), file.getSize(), file.getContentType(), key);

        String url = generateUrl(key);

        Map<String, String> data = new HashMap<>();
        data.put("url", url);

        logger.info("upload end,res:{}", JSONObject.toJSONString(data));
        return Response.success(data);
    }
    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        return UUID.randomUUID()+suffix;
    }
    private String generateUrl(String keyName) {
        return storage.generateUrl(keyName);
    }
}
